const fs = require('fs')
const XLSX = require('xlsx')
const { workArea } = require('./config.js');
const workerpool = require('workerpool');

async function createFiles(taskData) {
    const { fileName, userId } = taskData;
    const folder = `upload-tool(node)/static/${fileName.split('.')[0]}`
    // 发送方数据统计脚本
    let SheetData = []
    let PoData = []
    let DwData = []
    let files = []
    const toplimit = 1048575
    try {
        files = fs.readdirSync(`../${folder}/数据整理/${userId}/发送方`);
    } catch (error) { }
    files.map((fileName, i) => {
        let file = ''
        try {
            file = XLSX.readFile(`../${folder}/数据整理/${userId}/发送方/${fileName}`)
        } catch (error) {
            console.log(`${userId}发送方加密文件:${i + 1}`);
            return undefined
        }
        workArea.map((v, idx) => {
            v.map((val) => {
                const worksheet = file.Sheets[val];
                if (!worksheet) return undefined
                const data = XLSX.utils.sheet_to_json(worksheet, {
                    defval: "" // 空单元格返回空字符串，而不是 undefined
                });
                data.forEach((v) => {
                    const A1 = Object.keys(v)[0]
                    const B1 = Object.keys(v)[1]
                    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
                    SheetData.push({ '名字': A1, '身份证号': B1 })
                    if (idCardRegex.test(v[A1])) {
                        if (idx == 0) {
                            SheetData.push({ '名字': v[B1], '身份证号': v[A1] })
                        }
                        if (idx == 1) {
                            PoData.push({ '名字': v[B1], '身份证号': v[A1] })
                        }
                        if (idx == 2) {
                            DwData.push({ '名字': v[B1], '身份证号': v[A1] })
                        }
                    }
                    if (idCardRegex.test(v[B1])) {
                        if (idx == 0) {
                            SheetData.push({ '名字': v[A1], '身份证号': v[B1] })
                        }
                        if (idx == 1) {
                            PoData.push({ '名字': v[A1], '身份证号': v[B1] })
                        }
                        if (idx == 2) {
                            DwData.push({ '名字': v[A1], '身份证号': v[B1] })
                        }
                    }
                })
            })
        })
    })
    // 添加工作表并创建文件
    const workbook = XLSX.utils.book_new();
    if (SheetData.length < toplimit) {
        SheetData = Array.from(new Map(SheetData.map(item => [item['身份证号'], item])).values());
        const Sheet = XLSX.utils.json_to_sheet(SheetData);
        XLSX.utils.book_append_sheet(workbook, Sheet, workArea[0][0]);
    } else {
        let result = []
        SheetData = Array.from(new Map(SheetData.map(item => [item['身份证号'], item])).values());
        for (let i = 0; i < SheetData.length; i += toplimit) {
            result.push(SheetData.slice(i, i + toplimit));
        }
        for (let sheetIndex = 0; sheetIndex < result.length; sheetIndex++) {
            const Sheet = XLSX.utils.json_to_sheet(result[sheetIndex]);
            XLSX.utils.book_append_sheet(workbook, Sheet, workArea[0][0] + (sheetIndex + 1));
        }
        XLSX.writeFile(workbook, `../${folder}/数据整理/${userId}/发送方/发送方-${SheetData.length}条数据.xlsx`);
    }
    if (PoData.length) {
        PoData = Array.from(new Map(PoData.map(item => [item['身份证号'], item])).values());
        const PO = XLSX.utils.json_to_sheet(PoData);
        XLSX.utils.book_append_sheet(workbook, PO, workArea[1][0]);
    }
    if (DwData.length) {
        DwData = Array.from(new Map(DwData.map(item => [item['身份证号'], item])).values());
        const DW = XLSX.utils.json_to_sheet(DwData);
        XLSX.utils.book_append_sheet(workbook, DW, workArea[2][0]);
    }
    try {
        SheetData.length && XLSX.writeFile(workbook, `../${folder}/数据整理/${userId}/发送方/发送方-${SheetData.length}条数据.xlsx`);
    } catch (error) {
        console.log(`${userId}没有发送方,找不到发送方文件夹`);
    }
    // 接收方数据统计脚本
    let SheetData2 = []
    let PoData2 = []
    let DwData2 = []
    let files2 = []
    try {
        files2 = fs.readdirSync(`../${folder}/数据整理/${userId}/接收方`);
    } catch (error) {
        return undefined
    }
    files2.map((fileName, i2) => {
        let file = ''
        try {
            file = XLSX.readFile(`../${folder}/数据整理/${userId}/接收方/${fileName}`)
        } catch (error) {
            console.log(`${userId}接收方加密文件:${i2 + 1}`);
            return undefined
        }
        // 遍历工作表
        workArea.map((v, idx) => {
            v.map((val) => {
                const worksheet = file.Sheets[val];
                if (!worksheet) return undefined
                const data = XLSX.utils.sheet_to_json(worksheet, {
                    defval: "" // 空单元格返回空字符串，而不是 undefined
                });
                data.forEach((v) => {
                    const A1 = Object.keys(v)[0]
                    const B1 = Object.keys(v)[1]
                    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
                    SheetData2.push({ '名字': A1, '身份证号': B1 })
                    if (idCardRegex.test(v[A1])) {
                        if (idx == 0) {
                            SheetData2.push({ '名字': v[B1], '身份证号': v[A1] })
                        }
                        if (idx == 1) {
                            PoData2.push({ '名字': v[B1], '身份证号': v[A1] })
                        }
                        if (idx == 2) {
                            DwData2.push({ '名字': v[B1], '身份证号': v[A1] })
                        }
                    }
                    if (idCardRegex.test(v[B1])) {
                        if (idx == 0) {
                            SheetData2.push({ '名字': v[A1], '身份证号': v[B1] })
                        }
                        if (idx == 1) {
                            PoData2.push({ '名字': v[A1], '身份证号': v[B1] })
                        }
                        if (idx == 2) {
                            DwData2.push({ '名字': v[A1], '身份证号': v[B1] })
                        }
                    }
                })
            })
        })
    })
    const workbook2 = XLSX.utils.book_new();
    if (SheetData2.length < toplimit) {
        SheetData2 = Array.from(new Map(SheetData2.map(item => [item['身份证号'], item])).values());
        const Sheet2 = XLSX.utils.json_to_sheet(SheetData2);
        XLSX.utils.book_append_sheet(workbook2, Sheet2, workArea[0][0]);
    } else {
        let result = []
        SheetData2 = Array.from(new Map(SheetData2.map(item => [item['身份证号'], item])).values());
        for (let i = 0; i < SheetData2.length; i += toplimit) {
            result.push(SheetData2.slice(i, i + toplimit));
        }
        for (let sheetIndex = 0; sheetIndex < result.length; sheetIndex++) {
            const Sheet = XLSX.utils.json_to_sheet(result[sheetIndex]);
            XLSX.utils.book_append_sheet(workbook2, Sheet, workArea[0][0] + (sheetIndex + 1));
        }
        XLSX.writeFile(workbook2, `../${folder}/数据整理/${userId}/接收方/接收方-${SheetData2.length}条数据.xlsx`);
    }
    if (PoData2.length) {
        PoData2 = Array.from(new Map(PoData2.map(item => [item['身份证号'], item])).values());
        const PO2 = XLSX.utils.json_to_sheet(PoData2);
        XLSX.utils.book_append_sheet(workbook2, PO2, workArea[1][0]);
    }
    if (DwData2.length) {
        DwData2 = Array.from(new Map(DwData2.map(item => [item['身份证号'], item])).values());
        const DW2 = XLSX.utils.json_to_sheet(DwData2);
        XLSX.utils.book_append_sheet(workbook2, DW2, workArea[2][0]);
    }
    try {
        SheetData2.length && XLSX.writeFile(workbook2, `../${folder}/数据整理/${userId}/接收方/接收方-${SheetData2.length}条数据.xlsx`);
    } catch (error) {
        console.log(`${userId}没有接收方,找不到接收方文件夹`);
    }
    let SheetData3 = [...SheetData, ...SheetData2]
    const workbook3 = XLSX.utils.book_new();
    if (SheetData3.length < toplimit) {
        SheetData3 = Array.from(new Map(SheetData3.map(item => [item['身份证号'], item])).values());
        const Sheet = XLSX.utils.json_to_sheet(SheetData3);
        XLSX.utils.book_append_sheet(workbook3, Sheet, workArea[0][0]);
    } else {
        let result = []
        SheetData3 = Array.from(new Map(SheetData3.map(item => [item['身份证号'], item])).values());
        for (let i = 0; i < SheetData3.length; i += toplimit) {
            result.push(SheetData3.slice(i, i + toplimit));
        }
        for (let sheetIndex = 0; sheetIndex < result.length; sheetIndex++) {
            const Sheet = XLSX.utils.json_to_sheet(result[sheetIndex]);
            XLSX.utils.book_append_sheet(workbook3, Sheet, workArea[0][0] + (sheetIndex + 1));
        }
    }
    SheetData3.length && XLSX.writeFile(workbook3, `../${folder}/数据整理/${userId}/汇总-${SheetData3.length}条数据.xlsx`);
}

workerpool.worker({ createFiles });